package com.gaogzhen.threadPool.scheduledThreadPool;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 定期维护：每周4 4:00:00执行维护工作
 * @author Administrator
 */
@Slf4j(topic = "c.RegularMaintenance")
public class RegularMaintenance {
    public static void main(String[] args) {
        // 1、获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 2、确定第一个周4的时间
        LocalDateTime time = now.withHour(4).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
        // 如果当前时间晚于本周4 4:00:00,那么计算得出的时间在延后1周即可
        if (now.compareTo(time) > 0) {
            time = time.plusWeeks(1);
        }
        // 3、执行定时任务
        long initialDelay = Duration.between(now, time).toMillis();
        long period = 7 * 24 * 3600 * 1000;
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(() -> {
            log.debug("定时维护任务开始执行...");
            log.debug("定时维护任务结束...");
        }, initialDelay, period, TimeUnit.MILLISECONDS);
    }
}
